using UnityEngine;
using System.Collections;

public class PlayerScript : MonoBehaviour {
	
	public int movementSpeed;
	public ParticleSystem particle_system;
	public bool isAlive = true;
	
	public int myHealth = 100;
	public Transform UIBar;
	private HealthBar HealthBarScript;
	Renderer m_mesh;
	void OnEnable()
	{
		Messenger<string>.AddListener("reset", ResetAsset);
	}
	
	void OnDisable()
	{
		Messenger<string>.RemoveListener("reset", ResetAsset);
	}
	
	public void OnAttack()
	{
		
	}
	public HealthBar HBar
	{
		get { return HealthBarScript; }
	}
	public int Health
	{
		get { return myHealth; }
		set { myHealth = value; if(myHealth <= 0) { playerDies(); }  HealthBarScript.SetBarValue(myHealth);}
	}
	
	void Awake()
	{
	}
	void OnSpawned()
	{
	
	}
	// Use this for initialization
	void Start () 
	{
			m_mesh = transform.FindChild("Cylinder002").renderer;
	
	 isAlive = true;
	}
	//OnControllerColliderHit
	
	public void playerDies(){
		//particle_system.Emit(30);
		if (isAlive) 
		{ 
			Debug.Log("Particle Started"); 
			particle_system.Play(); 
			isAlive = false; 
			FadeMaterial.Do(m_mesh.material, EZAnimation.ANIM_MODE.To, Color.clear, EZAnimation.GetInterpolator(EZAnimation.EASING_TYPE.Linear), 0.5f, 0.0f, null, null);
			StartCoroutine("Despawn");
		} //emits 30 particles
	}
	
	IEnumerator Despawn()
	{
		
		yield return new WaitForSeconds(1.0f);
		PoolManager.Pools["Players"].Despawn(transform);
	}
	
	/*void OnTriggerStay(Collider col)
	{
		if (tag != "alien")
		{
		//if (col.gameObject.tag == "alien") { Debug.Log(col.gameObject.tag); }
		
			switch(col.gameObject.tag)
			{
			case "alien":
				AlienScript alienScript = col.gameObject.GetComponent<AlienScript>();
				if(alienScript.attacking == true && alienScript.myHealth > 0 && myHealth > 0)
				{
					alienScript.attackTimer += Time.deltaTime;
					if (alienScript.attackTimer > alienScript.attackDuration) {
						myHealth -= alienScript.attackDamage;
						alienScript.attackTimer = 0;
						alienScript.attacking = false;
						alienScript.FinishAttack();
						Debug.Log ("Setting Health" + myHealth);
						HealthBarScript.SetBarValue(myHealth);
					}
				} else alienScript.StartAttack();
				break;
			}
		}
	}*/
	
	// Update is called once per frame
	void Update () {
	
	}
	
	void ResetAsset (string winner){
		myHealth = 100;
		isAlive = true;
		HealthBarScript.SetMax(myHealth);
		// relocate if needed - 
		//transform.position = new Vector3(Random.Range (0.0F,1.0F), 1.5F, Random.Range (0,1.0F));
	}
	public	void SetUI(string _Player)
	{
					
		UIBar = GameObject.Find("UIElements").transform.FindChild(_Player + "UI");
			Debug.Log(UIBar);
		HealthBarScript = UIBar.FindChild("HealthBar").GetComponent<HealthBar>();
		
		HealthBarScript.SetMax(myHealth);
	}

}
